<?php
// +----------------------------------------------------------------------
// |     【PurchaseMain】Service服务类
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\common\service;

use think\facade\Db;
use think\facade\Request;
use app\common\model\PurchaseMain as M;
use app\common\model\PurchaseInfo as INFO_M;
use app\common\service\PurchaseInfo as INFO_S;
use app\common\validate\PurchaseMain as V;

class PurchaseMain{
    
    // 添加
    public static function goAdd($data,$callback=false){
        //验证
        $validate = new V;
        if(!$validate->scene('add')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
		
        try {
			$data=self::dataFormat($data,'add');
            $model=M::create($data['data']);
			return ['model'=>$data['data'],'info'=>$data['info'],'id'=>$model['id']];
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }
    
    // 编辑
    public static function goEdit($data,$id){
    	$where = is_array($id) ? $id : ['id'=>$id];
        //验证
        $validate = new V;
        if(!$validate->scene('edit')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
        try {
			$data=self::dataFormat($data,'edit');
             M::update($data['data'],$where);
			 return ['model'=>$data['data'],'info'=>$data['info']];
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 状态
    public static function goStatus($data,$id){
        $model = is_array($id) ? M::where($id)->find() : M::find($id);
        if ($model->isEmpty())  return ['msg'=>'数据不存在','code'=>201];
        try{
            $model->save($data);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 删除
    public static function goRemove($id, $pur_id = false) {
        try {
            Db::startTrans();
    
            if ($pur_id) {
                // 删除订单时，删除关联的所有子明细（根据 pur_id）
                $subRecords = M::withTrashed()
                    ->where('pur_id', $id)
                    ->select();
    
                foreach ($subRecords as $record) {
                    if ($record->delete_time) {
                        $record->force()->delete();
                    } else {
                        $record->delete();
                    }
                }
            } else {
                // 删除单个记录（根据主键 id）
                $record = M::withTrashed()->find($id);
                if (!$record) {
                    Db::rollback();
                    return ['msg' => '数据不存在', 'code' => 201];
                }
    
                if ($record->delete_time) {
                    $record->force()->delete();
                    INFO_S::goBatchRemove($ids);
                } else {
                    $record->delete();
                }
            }
    
            Db::commit();
            return ['msg' => '操作成功', 'code' => 200];
        } catch (\Exception $e) {
            Db::rollback();
            return ['msg' => '操作失败: ' . $e->getMessage(), 'code' => 201];
        }
    }

    // 批量删除
    public static function goBatchRemove($ids) {
        if (!is_array($ids)) return ['msg' => '数据不存在', 'code' => 201];
    
        try {
            // 开启事务保证原子性
            Db::startTrans();
    
            // 获取所有目标记录（包含已软删除的）
            $records = M::withTrashed()
                ->whereIn('id', $ids)
                ->select();
    
            // 分组处理
            foreach ($records as $record) {
                if ($record->delete_time) {
                    // 已软删除的记录：物理删除
                    $record->force()->delete();
                    INFO_S::goBatchRemove($ids);
                } else {
                    // 未软删除的记录：软删除
                    $record->delete();
                }
            }
    
            // 提交事务
            Db::commit();
    
            return ['msg' => '操作成功', 'code' => 200];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['msg' => '操作失败: ' . $e->getMessage(), 'code' => 201];
        }
    }

    // 获取列表
    public static function goRecycle($where = []){
        if (Request::isPost()){
            $ids = Request::param('ids');
            if (!is_array($ids)) return ['msg'=>'参数错误','code'=>'201'];
                try{
                    if(Request::param('type')){
                        $data = M::onlyTrashed()->whereIn('id', $ids)->select();
                        foreach($data as $k){
                            $k->restore();
                        }
                    }else{
                        M::destroy($ids,true);
                    }
                }catch (\Exception $e){
                    return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
                }
                return ['msg'=>'操作成功'];
            }
        //按用户名
        
        $limit = I('get.limit/d');
        
        $prefix = env('database.prefix'); // 获取表名前缀
        
        $list = M::onlyTrashed()
            ->alias('main')
            // 关联员工表
            ->leftJoin($prefix . 'staff_main staff', 'main.staff_id = staff.id')
            // 关联采购表
            ->leftJoin($prefix . 'purchase_info info', 'main.id = info.pur_id')
            // 按条件查询
            ->where($where)
            // 指定字段
            ->field("main.id,main.status,main.pur_sn,main.create_time,main.sketch,main.delivery,staff.name as staff_name,staff.short_name,staff.store_name,info.pur_id,info.fabric_code,info.fabric_name,info.color_code,info.color_hex,info.color_name,info.gary,info.count,info.unit,info.sup_name,info.sup_code,info.sup_color,info.exp_method,info.exp_name,info.kg_info,info.remark,info.pur_kind")
            // 排序
            ->order([
                'main.create_time' => 'desc',
            ])
            ->append(['create_time2'])
            // 分页
            ->paginate($limit);
            
        return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
    }
	
	//修改某个参数
	public static function setFieldValue($data,$where=[]){
		if(empty($where)){
			$model =  M::find($data['id']);
		}else{
			$model = M::where($where)->find();
		}
		if ($model->isEmpty())  return ['msg'=>'数据不存在','code'=>201];
		try{
		    $model->save([
		        $data['field'] => $data['value'],
		    ]);
			return ['msg'=>'操作成功'];
		}catch (\Exception $e){
		    return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
		}
	}
	
	// 预处理添加和修改的数据
	public static function dataFormat($data,$type='add'){
		
		if($type == 'add'){					//添加时才处理
			$data['pur_sn']=date('ymdHis').rand(100,999);
			$data['update_time']=time();
		}else if($type == 'edit'){			//修改时才处理
			//	计算手续费
			$data['update_time']=time();
		}
		// 无论修改还是添加都处理
		$data['create_time']=strtotime($data['create_time']);
		$data['year']=date('Y',$data['create_time']);
		$data['month']=date('m',$data['create_time']);
		$data['day']=date('d',$data['create_time']);
		$info=$data['info'];
		unset($data['info']);
		return ['data'=>$data,'info'=>$info];
	}
}
